package org.itcast.travel.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.itcast.travel.mapper.*;
import org.itcast.travel.pojo.*;
import org.itcast.travel.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BlogServiceImpl implements BlogService {
    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private LikeInfoMapper likeInfoMapper;

    @Autowired
    private CollectInfoMapper collectInfoMapper;

    @Autowired
    private LookInfoMapper lookInfoMapper;


    @Override
    public PageBean page(BlogQueryParam blogQueryParam) {
        // 先执行 count 查询
        long totalCount = blogMapper.count(blogQueryParam);
        PageHelper.startPage(blogQueryParam.getPage(), blogQueryParam.getPageSize(), false);
        Page<BlogAndUser> blogPage = blogMapper.page(blogQueryParam);
        List<BlogAndUser> blogs = blogPage.getResult();
        System.out.println("@!#@!$!0." + blogs);
        if (!CollectionUtils.isEmpty(blogs)) {
            //将每个Blog对象的ID值获取并存放如集合中
            List<Integer> blogIds = blogs.stream().map(Blog::getId).toList();
            //根据获取的blogId从数据库中获取对应图片
            List<Image> images = imageMapper.selectByBlogIds(blogIds);

            //将images列表中的每个对象按照对应blogId的方法进行分组成一个Map，键为blogId，职位对应Image对象
            Map<Integer, List<Image>> imageMap = images.stream().collect(Collectors.groupingBy(Image::getBlogId));
            //遍历blogs列表，使用getOrDefault方法从imageMap中获取对应Image列表，若无，则使用空列表
            blogs.forEach(blog -> blog.setImages(imageMap.getOrDefault(blog.getId(), Collections.emptyList())));
        }
        return new PageBean(totalCount, blogs);
    }

    @Override
    public PageBean pageById(Integer userId, BlogQueryParam blogQueryParam) {
        PageHelper.startPage(blogQueryParam.getPage(), blogQueryParam.getPageSize());
        Page<BlogAndUser> blogPage = blogMapper.pageById(userId, blogQueryParam);
        List<BlogAndUser> blogs = blogPage.getResult();

        if (!CollectionUtils.isEmpty(blogs)) {
            //将每个Blog对象的ID值获取并存放如集合中
            List<Integer> blogIds = blogs.stream().map(Blog::getId).toList();
            //根据获取的blogId从数据库中获取对应图片
            List<Image> images = imageMapper.selectByBlogIds(blogIds);

            //将images列表中的每个对象按照对应blogId的方法进行分组成一个Map，键为blogId，职位对应Image对象
            Map<Integer, List<Image>> imageMap = images.stream().collect(Collectors.groupingBy(Image::getBlogId));
            //遍历blogs列表，使用getOrDefault方法从imageMap中获取对应Image列表，若无，则使用空列表
            blogs.forEach(blog -> blog.setImages(imageMap.getOrDefault(blog.getId(), Collections.emptyList())));
        }
        return new PageBean(blogPage.getTotal(), blogs);
    }

    @Override
    public void delete(List<Integer> ids) {
        blogMapper.delete(ids);
        imageMapper.delete(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Blog blog) {
        //修改基础信息
        blog.setUpdateTime(LocalDateTime.now());
        blogMapper.update(blog);

        //修改图片
        //  1.先删除
        imageMapper.delete(Arrays.asList(blog.getId()));
        //  2.再新增
        Integer blogId = blog.getId();
        List<Image> images = blog.getImages();
        if (!CollectionUtils.isEmpty(images)) {
            images.forEach(image -> {
                image.setBlogId(blogId);
                image.setUploadTime(LocalDateTime.now());
            });
            imageMapper.insert(images);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateLike(Integer blogId, Integer userId) {
        Integer flag = likeInfoMapper.selectOneLike(blogId, userId);
        if (flag == 0) {
            blogMapper.addLike(blogId);
            likeInfoMapper.insert(blogId, userId);
        } else {
            blogMapper.subLike(blogId);
            likeInfoMapper.delete(blogId, userId);
        }
    }

    @Override
    public Integer selectOneLike(Integer blogId, Integer userId) {
        return likeInfoMapper.selectOneLike(blogId, userId);
    }

    @Override
    public PageBean getLike(BlogQueryParam blogQueryParam, Integer userId) {
        PageHelper.startPage(blogQueryParam.getPage(), blogQueryParam.getPageSize());
        Page<BlogAndUser> blogPage = blogMapper.pageLike(userId, blogQueryParam);
        List<BlogAndUser> blogs = blogPage.getResult();

        if (!CollectionUtils.isEmpty(blogs)) {
            //将每个Blog对象的ID值获取并存放如集合中
            List<Integer> blogIds = blogs.stream().map(Blog::getId).toList();
            //根据获取的blogId从数据库中获取对应图片
            List<Image> images = imageMapper.selectByBlogIds(blogIds);

            //将images列表中的每个对象按照对应blogId的方法进行分组成一个Map，键为blogId，职位对应Image对象
            Map<Integer, List<Image>> imageMap = images.stream().collect(Collectors.groupingBy(Image::getBlogId));
            //遍历blogs列表，使用getOrDefault方法从imageMap中获取对应Image列表，若无，则使用空列表
            blogs.forEach(blog -> blog.setImages(imageMap.getOrDefault(blog.getId(), Collections.emptyList())));
        }
        return new PageBean(blogPage.getTotal(), blogs);
    }

    @Override
    public Integer selectOneCollect(Integer blogId, Integer userId) {
        return collectInfoMapper.selectOneCollect(blogId, userId);
    }

    @Override
    public void updateCollect(Integer blogId, Integer userId) {
        Integer flag = collectInfoMapper.selectOneCollect(blogId, userId);
        if (flag == 0) {
            blogMapper.addCollect(blogId);
            collectInfoMapper.insert(blogId, userId);
        } else {
            blogMapper.subCollect(blogId);
            collectInfoMapper.delete(blogId, userId);
        }
    }

    @Override
    public PageBean getCollect(BlogQueryParam blogQueryParam, Integer userId) {
        PageHelper.startPage(blogQueryParam.getPage(), blogQueryParam.getPageSize());
        Page<BlogAndUser> blogPage = blogMapper.pageCollect(userId, blogQueryParam);
        List<BlogAndUser> blogs = blogPage.getResult();

        if (!CollectionUtils.isEmpty(blogs)) {
            //将每个Blog对象的ID值获取并存放如集合中
            List<Integer> blogIds = blogs.stream().map(Blog::getId).toList();
            //根据获取的blogId从数据库中获取对应图片
            List<Image> images = imageMapper.selectByBlogIds(blogIds);

            //将images列表中的每个对象按照对应blogId的方法进行分组成一个Map，键为blogId，职位对应Image对象
            Map<Integer, List<Image>> imageMap = images.stream().collect(Collectors.groupingBy(Image::getBlogId));
            //遍历blogs列表，使用getOrDefault方法从imageMap中获取对应Image列表，若无，则使用空列表
            blogs.forEach(blog -> blog.setImages(imageMap.getOrDefault(blog.getId(), Collections.emptyList())));
        }
        return new PageBean(blogPage.getTotal(), blogs);
    }

    @Override
    public void updateLook(Integer blogId, Integer userId) {
        int flag = lookInfoMapper.select(blogId,userId);
        if (flag == 0) {
            lookInfoMapper.insert(blogId,userId);
        }else {
            lookInfoMapper.update(blogId,userId);
        }
    }

    @Override
    public PageBean getLook(BlogQueryParam blogQueryParam, Integer userId) {
        PageHelper.startPage(blogQueryParam.getPage(), blogQueryParam.getPageSize());
        Page<BlogAndUser> blogPage = blogMapper.pageLook(userId, blogQueryParam);
        List<BlogAndUser> blogs = blogPage.getResult();

        if (!CollectionUtils.isEmpty(blogs)) {
            //将每个Blog对象的ID值获取并存放如集合中
            List<Integer> blogIds = blogs.stream().map(Blog::getId).toList();
            //根据获取的blogId从数据库中获取对应图片
            List<Image> images = imageMapper.selectByBlogIds(blogIds);

            //将images列表中的每个对象按照对应blogId的方法进行分组成一个Map，键为blogId，职位对应Image对象
            Map<Integer, List<Image>> imageMap = images.stream().collect(Collectors.groupingBy(Image::getBlogId));
            //遍历blogs列表，使用getOrDefault方法从imageMap中获取对应Image列表，若无，则使用空列表
            blogs.forEach(blog -> blog.setImages(imageMap.getOrDefault(blog.getId(), Collections.emptyList())));
        }
        return new PageBean(blogPage.getTotal(), blogs);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Blog blog) {
        //1.新增博客数据
        //补全属性
        blog.setCreateTime(LocalDateTime.now());
        blog.setUpdateTime(LocalDateTime.now());
        blogMapper.insert(blog);
        //2.新增博客图片数据
        Integer blogId = blog.getId();
        List<Image> images = blog.getImages();
        if (!CollectionUtils.isEmpty(images)) {
            images.forEach(image -> {
                image.setBlogId(blogId);
                image.setUploadTime(LocalDateTime.now());
            });
            imageMapper.insert(images);
        }
    }

    @Override
    public Blog getById(Integer id) {
        return blogMapper.getById(id);
    }

}
